<?php

/*
 * This file will perform the ajax for getting the routes for the search results.
 * This is being used by admRouteSetup.php.
 * 
 * Created by: Peter Agno Jr.
 * Date created: November 21, 2011
 * 
 * In parameters: routeId and routeName
 * Out parameters: route information for search results
 */

session_start();

// Start - Checker for those users who will just go to the page by typing directly in the url.
if ($_POST) {
    include('../includes/siteConfig.php');
    
    // connect to database
    $connect = mysql_connect($hostName,$rootName,$dBasePassword) or die ('Unable to connect!');
    mysql_select_db($dBaseName) or die ('Unable to select database!');
    
    // Get the data from post
    $routeId = $_POST['routeId'];
    $routeName = $_POST['routeName'];
    $mainDocName = $_POST['mainDocName'];
    
    // Prepare filter for routeId
    $filterRoute = "";
    if ( $routeId != "" ) {
        $filterRoute = "AND DR.routeId = '" . $routeId . "' ";
    }
    
    // Prepare filter for routeName
    if ( $routeName != "" ) {       
        $filterRoute = $filterRoute . "AND DR.routeName LIKE '%" . $routeName . "%' ";
    }
    
    // Prepare filter for $mainDocName
    if ( $mainDocName != "" ) {       
        $filterRoute = $filterRoute . "AND DS.documentName LIKE '%" . $mainDocName . "%' ";
    }
    
    // Prepare the query for getting the routes
    $query =
        "
            SELECT DR.routeId as routeId, DR.routeName as routeName, DS.documentName as documentName
            FROM DocumentRoute as DR, DocumentSetup as DS
            WHERE DR.documentSetupId = DS.documentSetupId AND DR.routeLastUpdated IS NULL
            ".$filterRoute."
            ORDER BY DR.routeName ASC
        ";
    $result = mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
    
    // Identify if there were querried routes
    if ( mysql_num_rows($result) > 0 ) {
        while ($row = mysql_fetch_array($result)) {
            $jsondata = array();
            $jsondata['routeId'] = $row['routeId'];
            $jsondata['routeName'] = $row['routeName'];
            $jsondata['mainDocName'] = $row['documentName'];
            $feed[] = $jsondata;
        }
        
        echo json_encode($feed);
    }
    else {
        echo json_encode(0);
    }
    
    mysql_free_result($result);
    mysql_close($connect);
}   // End - Checker for those users who will just go to the page by typing directly in the url.
else {
    echo "You are not authorized to view this page. This incident will be reported immediately.";
}
?>
